#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
from django.core.exceptions import FieldError
import json

from django.db.models import Q

from repository import models
from api.utils import JsonEncoder
from django.db import transaction
import traceback

"""库存和操作记录相关操作"""


def get_stock_overview(desc=False, **conditions):
    """传入查询条件，获取库存表总览
    Args:
       desc: 是否降序
       conditions: 查询条件字典,如:{'code':'AAA'}

    Return:
        res: {
          'status': 200,    # 状态码，200为正常返回；400为入参错误
          'data': [],    query_set列表
          'detail': ''    # 错误详情
        }
    """
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }
    try:
        if desc:
            order = '-id'
        else:
            order = 'id'
        query_res = []
        stock_list = models.StockInfo.objects.filter(**conditions).prefetch_related('operationrecord_set').order_by(order)
        for stock in stock_list:
            last_operation = stock.operationrecord_set.prefetch_related('operator').last()
            if last_operation:
                if(last_operation.operator):
                    last_operator = last_operation.operator.username
                else:
                    last_operator = '已被删除'
                last_update = last_operation.created_at
            else:
                last_operator = ''
                last_update = ''

            s = {
                'id': stock.id,
                'code': stock.code,
                'name': stock.name,
                'stock': stock.stock,
                'threshold': stock.threshold,
                'unit': stock.unit,
                'lastOperator': last_operator,
                'lastUpdate': last_update
            }
            query_res.append(s)
    except FieldError:
        res['status'] = 400
        res['detail'] = '入参错误'
    else:
        res['data'] = query_res
    return json.dumps(res,cls=JsonEncoder)


def get_stock_info(*filter_fields,**conditions):
    """获取某一个库存的状态"""
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }
    try:
        query_res = models.StockInfo.objects.filter(**conditions).values(*filter_fields).first()
    except Exception:
        res['status'] = 500
        res['detail'] = '系统错误'
    else:
        res['data'] = query_res
    # print(res)
    return json.dumps(res, cls=JsonEncoder)


def save_operation_record(instance=None,filter_fields=None,**validated_data):
    """对operation_record进行create或update操作
        Args:
            instance: 原实例，update用
            filter_fields: 返回哪些字段给前端
            validated_data: 传入的合法数据
    """
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }

    try:
        with transaction.atomic():
            if not instance:    # 新增
                if not filter_fields:
                    filter_fields = []
                operation_record = models.OperationRecord.objects.create(**validated_data)
                stock_info_obj = models.StockInfo.objects.get(id=validated_data['stock_id'])
                if operation_record.operation_type == '1':
                    stock_info_obj.stock += operation_record.count
                elif operation_record.operation_type == '2':
                    stock_info_obj.stock -= operation_record.count
                stock_info_obj.save()
                query_res = models.OperationRecord.objects.filter(id=operation_record.id).values(*filter_fields).first()    # 为了获取关联表字段，需要查一次数据库
                res['data'] = query_res

                return json.dumps(res, cls=JsonEncoder)
            else:    # 修改
                pass
    except FieldError:
        res['status'] = 400
        res['detail'] = '入参错误'
    except Exception as e:
        res['status'] = 500
        res['detail'] = '出错啦'
        return json.dumps(res, cls=JsonEncoder)


def get_operation_record(stock_id,filter_fields=None):
    """获取某个库存的所有操作记录，倒序排列"""
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }
    try:
        query_res = list(models.OperationRecord.objects.filter(stock_id=stock_id).order_by('-id').values(*filter_fields).all())
    except FieldError:
        res['status'] = 400
        res['detail'] = '入参错误'
    else:
        res['data'] = query_res
    return json.dumps(res,cls=JsonEncoder)


def get_stock_list(desc=False,*filter_fields, **conditions):
    """获取所有库存信息
    Args:
        desc: Bollean, 是否倒序
        filter_fields: List, 要返回的字段
        conditions: Dict, 筛选条件
    """
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }

    try:
        if desc:
            order = '-id'
        else:
            order = 'id'
        query_res = list(models.StockInfo.objects.filter(**conditions).order_by(order).values(*filter_fields).all())
    except FieldError:
        res['status'] = 400
        res['detail'] = '入参错误'
    except Exception:
        res['status'] = 500
        res['detail'] = '系统错误'
    else:
        res['data'] = query_res
    return json.dumps(res, cls=JsonEncoder)


def save_stock_info(instance=None,*filter_fields,**validated_data):
    """对operation_record进行create或update操作
        Args:
            instance: 原实例，update用
            filter_fields: 返回哪些字段给前端
            validated_data: 传入的合法数据
    """
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }

    try:
        operator_id = validated_data.pop('operator_id')
        print(operator_id)
        with transaction.atomic():
            if not instance:    # 新增
                stock_info_obj =  models.StockInfo.objects.create(**validated_data)
                models.OperationRecord.objects.create(count=stock_info_obj.stock,
                                                      operation_type='3',
                                                      memo='初始化库存',
                                                      stock_id=stock_info_obj.id,
                                                      operator_id=operator_id)
                pk = stock_info_obj.id
            else:    # 修改
                pk = validated_data.pop('id')
                models.StockInfo.objects.filter(id=pk).update(**validated_data)
                models.OperationRecord.objects.create(count=validated_data.get('stock'),
                                                      operation_type='3',
                                                      memo='修改库存',
                                                      stock_id=pk,
                                                      operator_id=operator_id)

            query_res = models.StockInfo.objects.filter(id=pk).values(*filter_fields).first()  # 为了获取关联表字段，需要查一次数据库
            res['data'] = query_res
    except FieldError:
        traceback.print_exc()
        res['status'] = 400
        res['detail'] = '入参错误'
    except Exception as e:
        traceback.print_exc()
        res['status'] = 500
        res['detail'] = '出错啦'
    return json.dumps(res, cls=JsonEncoder)


def delete_stock(pk):
    """传入pk，删除库存"""
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }
    try:
        models.StockInfo.objects.filter(id=pk).delete()
    except Exception as e:
        traceback.print_exc()
        res['status'] = 500
        res['detail'] = '系统错误'
    return json.dumps(res)


def if_stock_duplicate(pk,code):
    """更新库存信息前，判断code是否和其他库存重复"""
    res = {
        'status': 200,
        'data': [],
        'detail': ''
       }
    try:
        res['data'] = models.StockInfo.objects.filter(~Q(id=pk) & Q(code=code)).exists()
    except Exception:
        traceback.print_exc()
        res['status'] = 500
        res['detail'] = '系统错误'
    return json.dumps(res)